<template>
  <div class="f-audio-box">
    <div class="audio-controls">
      <!-- 歌曲图片 -->
      <div class="music-img">
        <div class="music-cover">
          <img
            v-if="currentMusic && currentMusic.cover"
            :class="{ xuanzhun: rotateFlag }"
            :src="currentMusic && currentMusic.cover"
          />
          <div v-else class="noMusic" />
        </div>
      </div>
      <!-- 暂停，上一曲，下一曲 -->
      <div class="music-controls">
        <i class="iconfont icon-shangyiqu" @click="prevMusic" />
        <i
          v-if="rotateFlag"
          @click="pauseMussic"
          class="iconfont icon-zanting"
        ></i>
        <i v-else @click="musicPlay" class="iconfont icon-bofang"></i>
        <i class="iconfont icon-xiayiqu" @click="nextMusic"></i>
      </div>
      <!-- 进度条 -->
      <div class="progress-bar-box">
        <div class="music-name-box">
          <span class="music-name">{{
            (currentMusic && currentMusic.name) || "请选择音乐"
          }}</span>
        </div>
        <div class="progress-bar-box-bottom">
          <span class="musicsecond">{{ currentTime | s_to_hs }}</span>
          <div class="progress-bar" ref="progressBar">
            <div class="progress" :style="{ width: musicpProgress + '%' }" />
          </div>
          <span class="musicsecond">{{ musicduration | s_to_hs }}</span>
        </div>
      </div>
      <!-- music循环切换，音量 -->
      <div class="controls-right">
        <div v-if="volumeFlag" class="volume-box" ref="volumeBoxDom">
          <div class="volume-dom" ref="volumeDom" @click="changeVolume">
            <div
              class="volume-size"
              :style="{ height: volumeNum * 100 + '%' }"
            ></div>
          </div>
        </div>
        <div class="icon-box">
          <i
            class="iconfont icon-shengyin_shiti"
            ref="showVolumeIcon"
            @click="volumeFlag = !volumeFlag"
          ></i>
        </div>
        <div class="icon-box">
          <i
            class="iconfont loop-icon"
            :class="currentloopTypeList.icon"
            @click="switchLoopType"
          ></i>
        </div>
        <div class="icon-box">
          <i class="iconfont icon-liebiao" @click="showLyric = !showLyric"></i>
        </div>
      </div>
      <div class="LayricOrMusicBox" :class="{ height0: !showLyric }">
        <Layric
          ref="Layric"
          :layricTxt="currentMusic && currentMusic.lyric"
          class="Layric-parent-box"
        />
        <MusicList
          class="music-list-box"
          :musicIndex="musicIndex"
          :musicLIst="list"
          :lsMusicIndex.sync="lsMusicIndex"
          @switchMusic="switchMusic"
          v-on="$listeners"
        />
      </div>
    </div>
    <audio
      ref="f_audio"
      :controls="true"
      :loop="loopNum === 3"
      :src="(currentMusic && currentMusic.url) || ''"
    />
  </div>
</template>

<script>
import "./assets/iconfont/iconfont.css";
import Layric from "./components/lyric.vue";
import MusicList from "./components/musicList.vue";
export default {
  props: {
    list: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    Layric,
    MusicList,
  },
  data() {
    return {
      currentMusic: null, //当前音乐
      audioDom: null, //audio
      currentTime: 0, //音频播放进度（秒）
      musicduration: 0, //音频总长度
      loopNum: 1, //1:循环  2 随机  3 单曲
      rotateFlag: false, //旋转
      loopTypeList: [
        {
          id: 1,
          icon: "icon-xunhuan",
        },
        {
          id: 2,
          icon: "icon-suiji1",
        },
        {
          id: 3,
          icon: "icon-danquxunhuan",
        },
      ], //音乐播放模式
      volumeNum: 0, //音量
      volumeFlag: false, //音量是否显示
      lsMusicIndex: 0, //删除的时候用来存放当前的index
      showLyric: false, //是否显示歌词
    };
  },
  computed: {
    musicList() {
      return this.list;
    },
    musicpProgress() {
      return (this.currentTime / this.musicduration) * 100;
    },
    currentloopTypeList() {
      return this.loopTypeList.find((item) => item.id === this.loopNum);
    },
    musicIndex() {
      return this.musicList.findIndex(
        (item) => item.url === this.currentMusic.url
      );
    },
  },
  watch: {
    musicList: {
      deep: true,
      handler() {
        if (!this.currentMusic && this.musicList.length > 0) {
          // 当前没有播放的音乐且无音乐列表，播放音乐
          this.currentMusic = this.musicList[0];
          this.musicPlay();
        } else if (this.musicList.length === 0 && this.currentMusic) {
          // 音乐列表为空的时候清空当前音乐
          this.currentMusic = null;
          this.$refs.Layric.musicOver();
        } else {
          this.$refs.Layric.musicOver();
          this.currentMusic = this.musicList[this.lsMusicIndex || 0];
        }
      },
    },
  },
  mounted() {
    this.audioDom = this.$refs.f_audio;
    this.volumeNum = this.audioDom.volume;
    this.init();
  },
  filters: {
    //   秒转分
    s_to_hs: function (s) {
      //计算分钟
      //算法：将秒数除以60，然后下舍入，既得到分钟数
      var h;
      h = Math.floor(s / 60);
      //计算秒
      //算法：取得秒%60的余数，既得到秒数
      s = s % 60;
      //将变量转换为字符串
      h += "";
      s += "";
      //如果只有一位数，前面增加一个0
      h = h.length == 1 ? "0" + h : h;
      s = s.length == 1 ? "0" + s : s;
      return h + ":" + s;
    },
  },
  methods: {
    init() {
      this.audioDom.addEventListener("ended", () => {
        //   音频播放结束
        this.musicEnded();
        this.$refs.Layric.musicOver();
      });
      this.audioDom.addEventListener("seeked", () => {
        //   音频拖动进度条
        this.$refs.Layric.seekedFn(this.audioDom.currentTime);
      });
      this.audioDom.addEventListener("canplay", () => {
        //   当音乐可以播放的时候，且在暂停的时候播放
        if (this.audioDom.paused) {
          this.musicPlay();
        }
      });
      this.audioDom.addEventListener("timeupdate", () => {
        // 计算进度
        this.currentTime = parseInt(this.audioDom.currentTime);
        this.musicduration = parseInt(this.audioDom.duration) || 0;
        this.$refs.Layric.lyricGo(this.currentTime);
      });
      this.audioDom.addEventListener("pause", () => {
        this.rotateFlag = false;
      });
      this.audioDom.addEventListener("play", () => {
        this.rotateFlag = true;
      });
      this.audioDom.addEventListener("volumechange", () => {
        this.volumeNum = this.audioDom.volume;
      });
      let progressBarDom = this.$refs.progressBar;
      progressBarDom.addEventListener("click", (e) => {
        let num = (e.offsetX / progressBarDom.offsetWidth).toFixed(2);
        this.audioDom.currentTime = this.musicduration * num;
      });
      window.addEventListener("click", this.showOrhideVolume);
    },
    //播放音频
    musicPlay() {
      if (!this.currentMusic) return;
      this.$nextTick(() => {
        this.audioDom.play();
      });
    },
    // 暂停音频
    pauseMussic() {
      if (!this.currentMusic) return;
      this.$nextTick(() => {
        this.audioDom.pause();
      });
    },
    // 获取当前音乐的index值
    currentIndex() {
      return this.musicList.findIndex(
        (item) => item.url === this.currentMusic.url
      );
    },
    // 音乐播放结束事件
    musicEnded() {
      if (this.musicList.length === 0) return;
      if (this.loopNum === 1) {
        //   循环
        if (this.currentIndex() !== -1) {
          if (this.currentIndex() + 1 < this.musicList.length) {
            this.currentMusic = this.musicList[this.currentIndex() + 1];
          } else {
            this.currentMusic = this.musicList[0];
          }
        }
      } else if (this.loopNum === 2) {
        //   随机
        this.currentMusic = this.musicList[this.randomNum(this.currentIndex())];
      } else if (this.loopNum === 3) {
        // 单曲循环
      }
      this.musicPlay();
    },
    // 随机音乐
    randomNum(num) {
      let musicNum = Math.ceil(Math.random() * this.musicList.length - 1);
      if (num === musicNum) {
        return this.randomNum(num);
      }
      return musicNum;
    },
    // 切换音乐模式
    switchLoopType() {
      if (this.loopNum === 1) {
        this.loopNum = 2;
      } else if (this.loopNum === 2) {
        this.loopNum = 3;
      } else if (this.loopNum === 3) {
        this.loopNum = 1;
      }
    },
    // 改变音量
    changeVolume(e) {
      let maxVolume = this.$refs.volumeDom.offsetHeight;
      let clickHeight = e.target.offsetHeight - e.offsetY;
      this.audioDom.volume = (clickHeight / maxVolume).toFixed(2);
    },
    // 显示或者隐藏音量
    showOrhideVolume(e) {
      // 如果音量条没有，则阻止
      if (!this.$refs.volumeBoxDom) return;
      // 如果点击事件不在音量条或者喇叭位置，则隐藏音量
      if (
        !this.$refs.volumeBoxDom.contains(e.target) &&
        !this.$refs.showVolumeIcon.contains(e.target)
      ) {
        this.volumeFlag = false;
      }
    },
    // 切换音乐
    switchMusic(item) {
      this.$refs.Layric.musicOver();
      this.currentMusic = item;
    },
    // 下一曲
    nextMusic() {
      if (this.musicList.length === 1) return;
      this.$refs.Layric.musicOver();
      if (this.musicIndex === this.musicList.length - 1) {
        this.currentMusic = this.musicList[0];
      } else {
        this.currentMusic = this.musicList[this.musicIndex + 1];
      }
    },
    // 上一曲
    prevMusic() {
      if (this.musicList.length === 1) return;
      this.$refs.Layric.musicOver();
      if (this.musicIndex === 0) {
        this.currentMusic = this.musicList[this.musicList.length - 1];
      } else {
        this.currentMusic = this.musicList[this.musicIndex - 1];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.f-audio-box {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 60px;
  border: 1px solid #ccc;
}
.audio-controls {
  width: 100%;
  height: 100%;
  display: flex;
}
.music-img {
  flex: 0.8;
  display: flex;
  justify-content: center;
  align-items: center;
  .music-cover {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    overflow: hidden;
    img {
      width: 100%;
      height: 100%;
    }
    .noMusic {
      width: 100%;
      height: 100%;
      background: #333;
    }
  }
}
.music-controls {
  flex: 1.6;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  i {
    font-size: 30px;
  }
}
.progress-bar-box {
  flex: 6;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  .music-name-box {
    padding-left: 2%;
    .music-name {
      font-size: 16px;
    }
  }
  .progress-bar-box-bottom {
    display: flex;
    align-items: center;
    justify-content: space-around;
    .musicsecond {
      font-size: 14px;
    }
    .progress-bar {
      width: 80%;
      position: relative;
      background: #ccc;
      height: 6px;
      .progress {
        position: absolute;
        height: 6px;
        top: 0;
        left: 0;
        background: #c70c0c;
        display: inline-block;
        border-radius: 2px;
      }
    }
  }
}
.controls-right {
  width: 80px;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  .icon-box {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    i {
      font-size: 24px;
    }
  }
  .volume-box {
    position: absolute;
    height: 150px;
    width: 40px;
    z-index: 19;
    border: 1px solid #ccc;
    top: -152px;
    display: flex;
    .volume-dom {
      height: 80%;
      width: 6px;
      background: #ccc;
      margin: auto;
      display: flex;
      align-items: flex-end;
      .volume-size {
        width: 6px;
        background: #c70c0c;
      }
    }
  }
}
.LayricOrMusicBox {
  position: absolute;
  width: 100%;
  height: 300px;
  border: 1px solid #ccc;
  bottom: 100%;
  left: -1px;
  display: flex;
  z-index: 9;
  transition: 0.5s;
  overflow: hidden;
  .Layric-parent-box,
  .music-list-box {
    flex: 1;
  }
}
.height0 {
  height: 0px;
}

// 旋转
.xuanzhun {
  -webkit-transition-property: -webkit-transform;
  -webkit-transition-duration: 1s;
  -moz-transition-property: -moz-transform;
  -moz-transition-duration: 1s;
  -webkit-animation: rotate 3s linear infinite;
  -moz-animation: rotate 3s linear infinite;
  -o-animation: rotate 3s linear infinite;
  animation: rotate 3s linear infinite;
}
@-webkit-keyframes rotate {
  from {
    -webkit-transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
  }
}
@-moz-keyframes rotate {
  from {
    -moz-transform: rotate(0deg);
  }
  to {
    -moz-transform: rotate(359deg);
  }
}
@-o-keyframes rotate {
  from {
    -o-transform: rotate(0deg);
  }
  to {
    -o-transform: rotate(359deg);
  }
}
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(359deg);
  }
}
</style>